using System;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;

namespace WLWPluginBase.Utils
{
    /// <summary>
    /// Provides helper methods to manage configuration-related elements.
    /// </summary>
    public static class ConfigUtil
    {
        #region Peristence
        /// <summary>
        /// Loads the contents of the given configuration file into the given configuration object.
        /// </summary>
        /// <typeparam name="T">Type of object to load.</typeparam>
        /// <param name="configFile">Path and name of the configuration file to load.</param>
        /// <remarks>
        /// If <c>config</c> is <c>null</c>, a new instance of type <c>T</c> is created.
        /// </remarks>
        /// <returns>Populated <c>config</c> object.</returns>
        public static T LoadConfig<T>(string configFile) where T : new()
        {
            // Create a default configuration instanace.
            T config = new T();
            try
            {
                XmlSerializer serializer = new XmlSerializer(config.GetType());
                TextReader reader = new StreamReader(configFile);
                config = (T) serializer.Deserialize(reader);
                reader.Close();
            }
            catch (Exception ex)
            {
                // Ignore errors while loading the configuration.
                Debug.Write(ex.Message);
            }
            // Return the result of the operation.
            return config;
        }
        /// <summary>
        /// Stores the contents of the given configuration object in the given file location.
        /// </summary>
        /// <typeparam name="T">Type of object to load.</typeparam>
        /// <param name="configFile">Path and name of the configuration file to load.</param>
        /// <param name="config">Object instance representing the contents to be populated</param>
        public static void StoreConfig<T>(string configFile, T config)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(config.GetType());
                TextWriter writer = new StreamWriter(configFile);
                serializer.Serialize(writer, config);
                writer.Close();
            }
            catch (Exception ex)
            {
                // Ignore errors while storing the configuration.
                Debug.Write(ex.Message);
            }
        }
        #endregion Peristence
    }
}
